from flask_script import Manager,Server
from flask_migrate import Migrate,MigrateCommand
from app import db,app
from flask import request,jsonify
from utils.Myjwt import myjwt
import time
#注册蓝图
from application.views.users.user import user_blue
from application.views.users.login import login_blue
from application.views.users.kecheng import ke_blue
from application.views.users.gouwu import gou_blue
app.register_blueprint(user_blue)
app.register_blueprint(login_blue)
app.register_blueprint(ke_blue)
app.register_blueprint(gou_blue)
# # 生成管理工具对象
# manager = Manager(app)
# # 添加服务器运行指令
# manager.add_command("runserver",Server(host='0.0.0.0',use_debugger=True))
from flask_sockets import Sockets
socket = Sockets(app)
socketdict = {}
userlist = []
import json
@socket.route("/sockconn")
def sockconn(ws):
    id = request.args.get("id")
    if id != "kefu":
        userlist.append(id)
    socketdict[id] = ws
    print(socketdict)
    while not ws.closed:
        print("#####")
        message = ws.receive()  # 接收到消息
        print('接收到的消息',message)
        mes = json.loads(message)
        key = mes['send']
        if key != "conn":
            sendmes = json.dumps({"meslist": mes['mes'], "userlist": userlist})
            print(socketdict[key])
            socketdict[key].send(sendmes)
        else:
            ws.send(message)
import paramiko
def _ssh(host, username, password, port=22):
    client = paramiko.SSHClient()

    # 2.解决问题:如果之前没有，连接过的ip，会出现选择yes或者no的操作，
    ##自动选择yes
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        # 3.连接服务器
        client.connect(hostname=host,
                       port=22,
                       username=username,
                       password=password)
        channle = client.invoke_shell(term='xterm')
        return channle
    except:
        return False
def recv_ssh_msg(channle, ws):
    '''
    channle: 建立好的SSH连接通道 这个函数会不停的接收ssh通道返回的命令 返回到前端的ws套接字里
    '''
    while not channle.exit_status_ready():
        try:
            buf = channle.recv(1024)  # 接收命令的执行结果

            print("buff:::", buf.decode())
            ws.send(buf.decode())  # 向Websocket通道返回 except:
            break
        except:
            pass
plist = []
import threading
@socket.route('/websocketconn')
def webssh(ws):
    channle = _ssh("101.43.237.209", username="root", password="fjx158399.")

    '''
1: 接收前端(ws)的命令，发给后台(ssh) 2: 接收后台的返回结果，给到前端
'''
    while not ws.closed:
        message = ws.receive()  # 接收到消息
        t = threading.Thread(target=recv_ssh_msg, args=(channle, ws))
        t.setDaemon(True)
        t.start()  # 线程开启
        channle.send(message)  # 由SSH通道转交给Linux环境 else: # 连接断开 跳出循环
# #数据库迁移
# Migrate(app,db)
# # 添加数据库的操作指令
# manager.add_command("db",MigrateCommand)

# @app.before_request
# def before_request():
#     # 设置一个白名单
#     whitelist = ['/getimg', '/sms', '/login']
#     url = request.path
#     if url not in whitelist:
#         # 判断当前访问的Url是否在白名单中，如果不在验证token
#         try:
#             token = request.headers['token']
#             # 获取token
#             # 调用jwt封装好的check_token对比
#             flag = myjwt.check(token)
#             if flag == True:
#                 # 如果通过验证过期时间
#                 payload = myjwt.jwt_decode(token)
#                 now = time.time()
#                 tnow = payload['data']['exp']
#                 if int(now) - int(tnow) > 3600:
#                     return jsonify({"code": 401, "msg": "token已过期"})
#             else:
#                 return jsonify({"code": 402, "msg": "token被篡改"})
#         except:
#             return jsonify({"code": 403, "msg": "没获取到token"})

#如果是以此脚本作为主脚本程序，就执行
if __name__ == '__main__':
    # manager.run()
    # app.run(port=8000)
    from gevent import pywsgi
    from geventwebsocket.handler import WebSocketHandler

    server = pywsgi.WSGIServer(("localhost", 5000), app, handler_class=WebSocketHandler)
    print("web server start ... ")
    server.serve_forever()












    